
try:
  from xml.etree import ElementTree # for Python 2.5 users
except ImportError:
  from elementtree import ElementTree

import gdata.calendar.service
import gdata.service
import atom.service
import gdata.calendar
import atom
import getopt
import sys
import string
import time
import datetime

class VocabularyReminder:
    def __init__(self, email, pwd):
        '''
        Login into google calendar;
        Well, again, I don't know how to check if login is failed
        Email -- User email
        pwd   -- User password
        '''
        
        #login
        self.calendar_service = gdata.calendar.service.CalendarService()
        self.calendar_service.ssl = False
        self.calendar_service.email = email
        self.calendar_service.password = pwd 
        self.calendar_service.source = 'Google-Calendar_Python_Sample-1.0'
        self.calendar_service.ProgrammaticLogin()
        #TODO check if login success
    def addItem(self, title,content, user):
        '''
        add an entry into google calendar to remind you of remember stuffs;
        content --  The content u want to insert into your calendar
        user -- yzh or gq
        '''
        #define a cycle
        calendarURL = ''
        if user == 'yzh':
            calendarURL = '/calendar/feeds/olp9vk6o5ac7roglkvc15c2i98@group.calendar.google.com/private/full'
        if user == 'gq':
            calendarURL = '/calendar/feeds/0cib5omqeaqtv810f7mvbjds6s@group.calendar.google.com/private/full'
        nowday    = datetime.date.today()
        secondDay   = nowday+datetime.timedelta(1);
        thirdDay    = nowday+datetime.timedelta(3);
        fourthDay   = nowday+datetime.timedelta(7);
        fifthDay    = nowday+datetime.timedelta(14);
        sixthDay    = nowday+datetime.timedelta(29);
        checkDay = [nowday, secondDay, thirdDay, fourthDay, fifthDay, sixthDay]
        failedDay = []
        #need to convert date that can be recongnised by GC.
        for i in range(0, 6):
            day = checkDay[i]
            retry = 0
            event = gdata.calendar.CalendarEventEntry()
            event.title = atom.Title(text = title)
            event.content = atom.Content(text = content)
            start_time = day.strftime('%Y-%m-%dT15:00:00.000Z')
            end_time = day.strftime('%Y-%m-%dT15:59:00.000Z')
            event.when.append(gdata.calendar.When(start_time=start_time, end_time=end_time))
            while retry < 3:     #keep retrying for 3 times
                time.sleep(2)   #wait for 2 secs
                try:
                    new_event = self.calendar_service.InsertEvent(event, calendarURL)
                except gdata.service.RequestError, e:
                    retry = retry + 1
                    success = 0
                    print "Failed to add item, trying "+str(retry)
                    print e
                    continue
                break
            if retry == 3:      #failed to add that elem into 
                print day," Failed, adding to failed list"
                failedDay.append(day)

        if len(failedDay) == 0:     #All item have been added succesfully
            return '''<HTML><BODY>
                Congratulations, your plan have been added to your google calendar,<br>
                Thanx for using this buggy system.
                </HTML></BODY>'''
        else:                       #Failed item is not empty, so need user to add item manually
            failedString = ''
            for day in failedDay:
                failedString += day.strftime('%Y-%m-%d')
                failedString += '<br>'
            return '''<HTML><BODY>
            Ooopse!!! I'm so sorry to inform you that some of the days are not able to add to your google calendar due to some porblem that caused by Google server(So that's not my problem, right? XD)<br>
            You have to add them manually, the days that are not able to add to your calendar are listed below<br>'''+failedString+'''Sorry for the inconvenience T_T
            </HTML></BODY>'''



    def createCalendar(self, name, color, summary, location):
        '''
        Create a calendar in google calendar
        You only have to create calendar once, but I don't know how to check if there is a duplication happens.
        name     --  calander name
        color    --  which color you want to use for this calendar, use hex expression.
        summary  --  Summary of your calendar
        location --  Where the things in the calendar may happen
        '''
        # Create the calendar
        calendar = gdata.calendar.CalendarListEntry()
        calendar.title = atom.Title(text=name)
        calendar.summary = atom.Summary(text=summary)
        calendar.where = gdata.calendar.Where(value_string=location)
        calendar.color = gdata.calendar.Color(value=color)
        calendar.timezone = gdata.calendar.Timezone(value='Asia/Shanghai')
        calendar.hidden = gdata.calendar.Hidden(value='false')
        new_calendar = calendar_service.InsertCalendar(new_calendar=calendar)
        #TODO check if calenar is successfully created



